/**
 * 
 */
package com.example.envatoandroid.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteException;

/**
 * @author niam
 *
 */
public class UserInfoDatabase implements DatabaseHelper
{
	private static UserInfoDatabase instance = null;
	private CommonDatabaseHelper commonDB;
	private SQLiteDatabase db;
	
	private String TABLE_NAME_USER_INFO = "user_info";
	private String COLUMN_ID = "pk_id";
	private String COLUMN_USER_NAME = "user_name";
	private String COLUMN_API_KEY = "api_key";
	
	private String CREATE_TABLE_USER_INFO = "CREATE TABLE " + TABLE_NAME_USER_INFO + " IF NOT EXISTS "
											+ "(" + COLUMN_ID + " INT NOT NULL AUTO_INCREMENT PRIMARY KEY " 
											+ COLUMN_USER_NAME + " VARCHAR(200) NOT NULL " 
											+ COLUMN_API_KEY + " VARCHAR(200) NOT NULL" + ");";
	
	private String[] ALL_COLUMNS = {COLUMN_USER_NAME, COLUMN_API_KEY};
		
	private UserInfoDatabase(Context context)
	{
		commonDB = CommonDatabaseHelper.getInstance(context);
		db = commonDB.getWritableDatabase();
	}
	
	public static UserInfoDatabase getInstance(Context context)
	{
		if (instance == null)
		{
			instance = new UserInfoDatabase(context);
		}
		return instance;
	}
	
	public void open()
	{
		try
		{
			if (!db.isOpen())
				db = commonDB.getWritableDatabase();
		}
		catch (SQLiteException e)
		{
			e.printStackTrace();
		}
	}
	
	public void close()
	{
		try
		{
			db.close();
		}
		catch (SQLiteException e)
		{
			e.printStackTrace();
		}
	}

	@Override
	public void onCreate(SQLiteDatabase db)
	{
		db.execSQL(CREATE_TABLE_USER_INFO);
	}

	@Override
	public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion)
	{
		
	}

	public long insert(UserInfoData userInfoData)
	{
		long id = -1;
		
		ContentValues cv = new ContentValues();
		cv.put(COLUMN_USER_NAME, userInfoData.getUserName());
		cv.put(COLUMN_API_KEY, userInfoData.getApiKey());
		
		id = db.insert(TABLE_NAME_USER_INFO, null, cv);
		
		return id;
	}

	public UserInfoData getData(String userName)
	{
		UserInfoData userInfoData = UserInfoData.getInstance();
		
		Cursor cursor = db.query(TABLE_NAME_USER_INFO, ALL_COLUMNS, " WHERE " + COLUMN_USER_NAME + " =? ", 
					new String[] {userName}, null, null, null);
		
		while(cursor.moveToNext())
		{
			userInfoData.setUserName(cursor.getString(0));
			userInfoData.setApiKey(cursor.getString(1));
		}
		
		return userInfoData;
	}
}
